<template>
  <div class="select_city_wrapper">
    <a-spin :spinning="spinning">
      <a-input class="search-input" v-model="treeSelectValue" @change="changeValue" @pressEnter="changeValue"/>
      <div class="clear">
        <span @click="clear"><i class="iconfont icon-shanchu" />清空</span>
      </div>
      <div class="have_select_city">
        <span>已选择</span>
        <span v-for="item in haveSelectCity" :key="item.id">
          <a class="badge" href="javascript:;" color="#0166b6" @click.stop="changeCity(item)">{{item.name}}</a>
        </span>
      </div>

      <div class="content">
        <a-tabs type="editable-card" :activeKey="activeKey" @change="changeTabs" @edit="editTabs" hideAdd>
          <a-tab-pane v-for="area in dataSource" :tab="area.name" :key="area.name" :closable="false">
            <template v-if="area.name === '大陆'">
              <template v-if="area.hideHotCity">
                <a-row :gutter="20">
                  <a-col :span='6' class="mb5" v-for="province in area.children" :key="province.id" v-show="province.filterShow">
                    <span v-if="province.children.length">
                      <a-checkbox @change="checkAll($event, province)" :checked="province.checkAll" :indeterminate="province.indeterminate"></a-checkbox>
                      <a href="javascript:;" class="blue_text province" @click="changeProvince(province)">{{province.name}}</a>
                    </span>
                    <span v-else>
                      <span style="display: inline-block; width: 16px;"></span>
                      <a href="javascript:;" class="blue_text province" :class="{ checkAll: province.checkAll  }" @click="changeProvince(province)">{{province.name}}</a>
                    </span>
                  </a-col>
                </a-row>
              </template>
              <template v-else>
                <a-row :gutter="20">
                  <a-col :span="24" class="mb5" style="color: #f5222d;">热门城市</a-col>
                  <a-col :span='6' class="mb5" v-for="province in area.children" :key="province.id" v-show="area.name === '大陆' && province.isHot === 'Y' && province.filterShow">
                    <span v-if="province.children.length">
                      <a-checkbox @change="checkAll($event, province)" :checked="province.checkAll" :indeterminate="province.indeterminate"></a-checkbox>
                      <a href="javascript:;" class="blue_text province" @click="changeProvince(province)">{{province.name}}</a>
                    </span>
                    <span v-else>
                      <span style="display: inline-block; width: 16px;"></span>
                      <a href="javascript:;" class="blue_text province" :class="{ checkAll: province.checkAll  }" @click="changeProvince(province)">{{province.name}}</a>
                    </span>
                  </a-col>
                </a-row>
                <a-row :gutter="20">
                  <a-col :span="24" class="mb5">其他省份</a-col>
                  <a-col :span='6' class="mb5" v-for="province in area.children" :key="province.id" v-show="province.isHot !== 'Y' && province.filterShow">
                    <span v-if="province.children.length">
                      <a-checkbox @change="checkAll($event, province)" :checked="province.checkAll" :indeterminate="province.indeterminate"></a-checkbox>
                      <a href="javascript:;" class="blue_text province" @click="changeProvince(province)">{{province.name}}</a>
                    </span>
                    <span v-else>
                      <span style="display: inline-block; width: 16px;"></span>
                      <a href="javascript:;" class="blue_text province" :class="{ checkAll: province.checkAll  }" @click="changeProvince(province)">{{province.name}}</a>
                    </span>
                  </a-col>
                </a-row>
              </template>
            </template>
            <template v-else>
              <a-row :gutter="20">
                <a-col :span='6' class="mb5" v-for="province in area.children" :key="province.id" v-show="province.filterShow">
                  <span v-if="province.children.length">
                    <span v-if="province.filterShow">
                      <a-checkbox @change="checkAll($event, province)" :checked="province.checkAll" :indeterminate="province.indeterminate"></a-checkbox>
                      <a href="javascript:;" class="blue_text province" @click="changeProvince(province)">{{province.name}}</a>
                    </span>
                  </span>
                  <span v-else>
                    <span v-if="province.filterShow">
                      <span style="display: inline-block; width: 16px;"></span>
                      <a href="javascript:;" class="blue_text province" :class="{ checkAll: province.checkAll  }" @click="changeProvince(province)">{{province.name}}</a>
                    </span>
                  </span>
                </a-col>
              </a-row>
            </template>
          </a-tab-pane>
          <a-tab-pane v-for="province in operatedProvinces" :tab="province.name" :key="province.id">
            <a-row :gutter="16">
              <a-col :span='6' class="mb5" v-for="city in province.children" :key="city.id" v-show="city.filterShow">
                <a href="javascript:;" class="blue_text city" :class="{ checked: city.checked }" @click="changeCity(city)">{{city.name}}</a>
              </a-col>
            </a-row>
          </a-tab-pane>
        </a-tabs>
      </div>
    </a-spin>
  </div>
</template>

<script>
import XEUtils from 'xe-utils'
export default {
  name: 'SelectCity',
  props: {
    dataSource: {
      type: Array,
      default: () => [],
      require: true
    },
    checkCity: {
      type: Array,
      default: () => []
    },
    defaultActiveKey: {
      type: String,
      default: '大陆',
      require: true
    },
    spinning: {
      type: Boolean,
      default: false
    },
    mode: {
      type: String,
      default: 'multiple' // single
    }
  },
  model: {
    prop: 'checkCity',
    event: 'change'
  },
  computed: {
    searchTreeData () {
      const crr = []
      this.dataSource.map(country => {
        const arr = XEUtils.toTreeArray(JSON.parse(JSON.stringify(country.children)))
        arr.forEach(item => {
          item.key = item.id
          item.value = item.id
          item.title = item.name
        })
        const brr = XEUtils.toArrayTree(JSON.parse(JSON.stringify(arr)), { key: 'id', parentKey: 'parentId' })
        brr.map(treeItem => {
          crr.push(treeItem)
        })
        console.log(brr)
      })
      return crr
    }
  },
  data () {
    return {
      XEUtils,
      operatedProvinces: [], // 已经选中可以进行操作的，市
      activeKey: '',
      haveSelectCity: [],
      treeToList: [],
      treeSelectValue: ''
      // searchTreeData: []
    }
  },
  mounted () {
    this.activeKey = this.defaultActiveKey
  },
  methods: {
    setChecked (arr) {
      arr.forEach((item) => {
        if (item.hasOwnProperty('checked')) {
          this.$set(item, 'checked', false)
        } else if (item.hasOwnProperty('checkAll')) {
          this.$set(item, 'checkAll', false)
        }
        if (item.children) {
          this.setChecked(item.children)
        }
      })
    },
    clear () {
      this.treeSelectValue = ''
      this.setChecked(this.dataSource)
      this.setChecked(this.checkCity)
    },
    checkAll (e, province) { // 全选checkbox 选中将下属children 清空
      if (this.mode === 'single') {
        this.checkAllFalse()
      }
      this.operate(province)
    },
    changeProvince (province) {
      if (province.children.length) {
        this.pushOperate(province)
        return
      }
      if (this.mode === 'single') {
        this.checkAllFalse()
      }
      this.operate(province)
    },
    changeCity (city) {
      if (this.mode === 'single') {
        this.checkAllFalse()
      }
      this.operate(city)
    },
    changeTabs (activeKey) {
      this.activeKey = activeKey
    },
    editTabs (targetKey, action) {
      if (action === 'remove') {
        this.removeProvince(targetKey)
      }
    },
    pushOperate (province) {
      const index = this.operatedProvinces.findIndex(item => item.id === province.id)
      if (index === -1) {
        this.operatedProvinces.push(province)
      }
      this.activeKey = province.id
    },
    operate (self) {
      // 选中子 父checkAll 都为false， 选中父 子checked都为false
      const selfId = self.id
      const parentId = self.parentId
      this.dataSource.forEach(country => {
        country.children && country.children.forEach(province => {
          province.children && province.children.forEach(city => {
            if (city.id === selfId) { // 选中自己checked 切换
              this.$set(city, 'checked', !city.checked)
              country.children && country.children.forEach(otherProvince => {
                otherProvince.children.forEach(otherCity => {
                  if (province.id === otherCity.id) {
                    this.$set(otherProvince, 'checkAll', false)
                  }
                })
              })
            }
            if (city.id === parentId) { // 选中的标签的parent 为其他标签的children， 将其他标签的children 置为false
              if (province.children.some(item => item.checked === true)) {
                this.$set(city, 'checked', false)
              }
            }
          })
          if (province.id === parentId) { // 将选中的标签的parent 的checkAll 置为false
            if (province.children.some(item => item.checked === true)) {
              this.$set(province, 'checkAll', false)
            }
          }
          if (province.id === selfId) { // 选中的标签作为其他标签的parent ，同步其他标签checkAll， 并清空其他标签下的children
            this.$set(province, 'checkAll', !province.checkAll)
            province.children && province.children.forEach(city => {
              country.children && country.children.forEach(otherProvince => {
                if (city.id === otherProvince.id) {
                  this.$set(otherProvince, 'checkAll', false)
                  otherProvince.children.forEach(city => {
                    this.$set(city, 'checked', false)
                  })
                }
              })
              this.$set(city, 'checked', false)
            })
          }
        })
      })
    },
    clearChildren () {

    },
    clearParent () {

    },
    listCity () {
      this.haveSelectCity = []
      this.dataSource.forEach(country => {
        country.children && country.children.forEach(province => {
          if (province.checkAll) {
            const index = this.haveSelectCity.findIndex(item => item.id === province.id)
            if (index === -1) {
              this.haveSelectCity.push(province)
            }
          }
          province.children && province.children.forEach(city => {
            if (city.checked) {
              const index = this.haveSelectCity.findIndex(item => item.id === city.id)
              if (index === -1) {
                this.haveSelectCity.push(city)
              }
            }
          })
        })
      })
    },
    removeProvince (targetKey) {
      let { activeKey, operatedProvinces } = this
      let lastIndex
      operatedProvinces.forEach((province, i) => {
        if (province.id === targetKey) {
          lastIndex = i - 1
        }
      })
      const panes = operatedProvinces.filter(pane => pane.id !== targetKey)
      if (lastIndex >= 0 && activeKey === targetKey) {
        activeKey = panes[lastIndex].id
      } else {
        activeKey = this.defaultActiveKey
      }
      this.operatedProvinces = panes
      this.activeKey = activeKey
    },
    checkAllFalse () { // 单选之前把所有的选中状态置为 false
      this.dataSource.forEach(country => {
        country.children && country.children.forEach(province => {
          this.$set(province, 'checkAll', false)
          province.children && province.children.forEach(city => {
            this.$set(city, 'checked', false)
          })
        })
      })
    },
    treeSelectChange (value) {
      console.log()
      console.log(value)
      this.treeSelectValue = value
      console.log(this.treeSelectValue)
      if (Array.isArray(value)) {
        this.treeToList.map(item => {
          value.map(id => {
            console.log(id)
            // if (id === item.id) {
            //   this.checkAllFalse()
            //   this.operate(item)
            // }
          })
        })
      } else if (value.constructor === String) {
        const obj = this.treeToList.find(item => item.id === value)
        if (this.mode === 'single') {
          this.checkAllFalse()
        }
        this.operate(obj)
      } else {
        this.clear()
      }
    },
    filterTreeNodeFn (inputValue, treeNode) {
      console.log(this.searchTreeData)
      if (treeNode.data && treeNode.data.props && treeNode.data.props.title && treeNode.data.props.title && treeNode.data.props.title.indexOf(inputValue) !== -1) {
        return true
      } else {
        return false
      }
    },
    changeValue () {
      // this.dataSource.forEach(item => {
      //   if (this.treeSelectValue) {
      //     if (item.name === this.activeKey) {
      //       let filterData = XEUtils.toTreeArray(this.rebuildData(this.treeSelectValue, item.children)).map(item => item.id)
      //       console.log(this.rebuildData(this.treeSelectValue, item.children))
      //       XEUtils.toTreeArray(item.children).forEach(element => {
      //         if (filterData.indexOf(element.id) !== -1) {
      //           element.filterShow = true
      //         } else {
      //           element.filterShow = false
      //         }
      //       })
      //       console.log(item.children)
      //     }
      //   } else {
      //     XEUtils.toTreeArray(item.children).forEach(element => {
      //       element.filterShow = true
      //     })
      //   }
      // })
      this.searchTree(this.dataSource, this.treeSelectValue, 'name')
      this.searchTree(this.operatedProvinces, this.treeSelectValue, 'id')
    },
    searchTree (dataSource, treeSelectValue, type) {
      // console.log(treeSelectValue, type)
      dataSource.forEach(item => {
        if (treeSelectValue) {
          if (item[type] === this.activeKey) {
            let filterData = XEUtils.toTreeArray(this.rebuildData(treeSelectValue, item.children)).map(item => item.id)
            XEUtils.toTreeArray(item.children).forEach(element => {
              if (filterData.indexOf(element.id) !== -1) {
                element.filterShow = true
              } else {
                element.filterShow = false
              }
            })
          }
        } else {
          XEUtils.toTreeArray(item.children).forEach(element => {
            element.filterShow = true
          })
        }
      })
    },
    rebuildData (value, arr) {
      let newarr = []
      arr.forEach(element => {
        if (element.name.indexOf(value) > -1) { // 判断条件
          newarr.push(element)
        } else {
          if (element.children && element.children.length > 0) {
            let redata = this.rebuildData(value, element.children)
            let obj = {
              ...element,
              children: redata
            }
            if (redata && redata.length > 0) {
              newarr.push(obj)
            }
          }
        }
      })
      return newarr
    }
  },
  watch: {
    dataSource: {
      handler (newValue, oldValue) {
        if (newValue && newValue.length) {
          this.treeToList = []
          this.listCity()
          newValue.forEach(country => {
            XEUtils.toTreeArray(country.children).map(item => {
              item.filterShow = true
              // this.treeToList.push(item)
            })
            country.children && country.children.forEach(province => {
              this.$set(province, 'indeterminate', province.children.some(item => item.checked === true) && !province.children.every(item => item.checked === true))
              if (province.children.some(item => item.checked === true)) {
                this.$set(province, 'checkAll', false)
              }
              if (province.checkAll) {
                province.children.forEach(city => {
                  this.$set(city, 'checked', false)
                })
              }
            })
          })
          this.$emit('change', newValue)
        }
      },
      deep: true,
      immediate: true
    }
    // haveSelectCity: {
    //   handler (newValue, oldValue) {
    //     this.treeSelectValue = this.haveSelectCity.map(item => item.id)
    //   }
    // }
  }
}
</script>
<style lang="stylus" scoped>
.select_city_wrapper
  .clear
    display flex
    justify-content flex-end
    align-items center
    margin-bottom 2px
    span
      cursor pointer
      i.iconfont
        vertical-align middle
  .have_select_city
    padding-bottom 20px
    .badge
      display inline-block
      margin 0 4px 2px 0
      padding 0 8px
      line-height 26px
      background-color #0166b6
      color #fff
      border-radius 13px
  .recent_select_city
    padding 20px 0
  .content
    .line
      background #eee
      height 10px
    .province
      display inline-block
      padding 4px
      &.checkAll
        background-color #0166b6
        color #fff
    .city
      display inline-block
      padding 4px
      &.checked
        background-color #0166b6
        color #fff
.search-input
  margin-bottom 10px
</style>
